package com.flowplan.project.repository;

import com.flowplan.entity.Project;
import com.flowplan.entity.enums.ProjectStatus;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 项目Repository接口
 * 
 * @author FlowPlan Team
 */
@Repository
public interface ProjectRepository extends JpaRepository<Project, Long> {
    
    /**
     * 根据项目名称查找项目
     */
    Optional<Project> findByProjectName(String projectName);
    
    /**
     * 根据创建人ID查找项目列表
     */
    List<Project> findByCreatorIdOrderByCreateTimeDesc(Long creatorId);
    
    /**
     * 根据状态查找项目列表
     */
    List<Project> findByStatusOrderByCreateTimeDesc(ProjectStatus status);
    
    /**
     * 分页查询项目列表
     */
    Page<Project> findAllByOrderByCreateTimeDesc(Pageable pageable);
    
    /**
     * 根据条件分页查询项目
     */
    @Query("SELECT p FROM Project p WHERE " +
           "(:status IS NULL OR p.status = :status) AND " +
           "(:creatorId IS NULL OR p.creatorId = :creatorId) AND " +
           "(:keyword IS NULL OR p.projectName LIKE %:keyword% OR p.description LIKE %:keyword%) " +
           "ORDER BY p.createTime DESC")
    Page<Project> findProjectsWithConditions(
            @Param("status") ProjectStatus status,
            @Param("creatorId") Long creatorId,
            @Param("keyword") String keyword,
            Pageable pageable);
    
    /**
     * 查找即将到期的项目（7天内）
     */
    @Query("SELECT p FROM Project p WHERE " +
           "p.deadline IS NOT NULL AND " +
           "p.deadline BETWEEN :now AND :deadlineLimit AND " +
           "p.status NOT IN ('COMPLETED', 'CANCELLED')")
    List<Project> findProjectsNearDeadline(
            @Param("now") LocalDateTime now,
            @Param("deadlineLimit") LocalDateTime deadlineLimit);
    
    /**
     * 查找已过期的项目
     */
    @Query("SELECT p FROM Project p WHERE " +
           "p.deadline IS NOT NULL AND " +
           "p.deadline < :now AND " +
           "p.status NOT IN ('COMPLETED', 'CANCELLED')")
    List<Project> findOverdueProjects(@Param("now") LocalDateTime now);
    
    /**
     * 统计用户创建的项目数量
     */
    @Query("SELECT COUNT(p) FROM Project p WHERE p.creatorId = :creatorId")
    Long countByCreatorId(@Param("creatorId") Long creatorId);
    
    /**
     * 统计各状态的项目数量
     */
    @Query("SELECT p.status as status, COUNT(p) as count FROM Project p GROUP BY p.status")
    List<Object[]> countProjectsByStatus();
}